package cn.swust.action;

import java.util.Date;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsStatics;

import cn.swust.model.AdminBean;
import cn.swust.model.UserBean;
import cn.swust.service.AdminService;
import cn.swust.service.UserService;
import cn.swust.service.serviceimpl.AdminServiceImpl;
import cn.swust.service.serviceimpl.UserServiceImpl;
import cn.swust.util.CookieUtil;
import cn.swust.util.LoginMess;
import cn.swust.util.sendJson;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport {
	private static final long serialVersionUID = 1L;
	private String userName;
	private String password;

	public String login() {
		Map<String, Object> session = ActionContext.getContext().getSession();
		UserService user = new UserServiceImpl();
		UserBean userBean = user.queryByName(userName);
		String userPwd = userBean.getPassword();
		LoginMess msg = new LoginMess();
		if (password.equals(userPwd)) {
			if (!session.containsKey(userName)) {
				session.put("username", userName);
			}
			msg.setFlag(1);
			msg.setMessage("登录成功");
			msg.setUserName(userName);

			HttpServletResponse response = ServletActionContext.getResponse();
			// poor 表示为贫困生，common 表示普通
			Cookie userinInfo = new Cookie("loginInfo", userBean.getName()
					+ "|" + userBean.getPassword() + "|poor");
			userinInfo.setPath("/");
			userinInfo.setMaxAge(2678400);// 有效期31天
			Cookie isLogin = new Cookie("isLogin", "true");
			isLogin.setPath("/");
			response.addCookie(userinInfo);
			response.addCookie(isLogin);
			sendJson.send(response, msg);
			return null;
		} else {
			msg.setFlag(0);
			msg.setMessage("你的用户名或者密码错误！");
			sendJson.send(ServletActionContext.getResponse(), msg);
			return null;
		}
	}

	public String logout() {
		ActionContext.getContext().getSession().clear();
		LoginMess msg = new LoginMess();
		msg.setFlag(1);
		sendJson.send(ServletActionContext.getResponse(), msg);
		return null;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}
